package com.example.monitor.service.impl;

import com.example.monitor.model.DTO.UserAbnormalTypeQueryDTO;
import com.example.monitor.model.VO.ResultVO;
import com.example.monitor.model.VO.UserAbnormalTypeVO;
import com.example.monitor.repository.AlarmRecordRepository;
import com.example.monitor.service.UserAbnormalTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserAbnormalTypeServiceImpl implements UserAbnormalTypeService {

    private final AlarmRecordRepository alarmRecordRepository;

    @Override
    public ResultVO<List<UserAbnormalTypeVO>> getUserAbnormalTypeDistribution(UserAbnormalTypeQueryDTO queryDTO) {
        // 查询原始数据
        List<Object[]> rawData = alarmRecordRepository.countAbnormalTypesByWorker(queryDTO.getWorkerId());

        // 计算总数用于计算百分比
        int total = rawData.stream()
                .mapToInt(arr -> ((Number)arr[1]).intValue())
                .sum();

        // 转换为VO列表
        List<UserAbnormalTypeVO> result = rawData.stream()
                .map(arr -> new UserAbnormalTypeVO(
                        (String) arr[0],
                        ((Number) arr[1]).intValue(),
                        total > 0 ?
                                Math.round(((Number)arr[1]).doubleValue() / total * 100 * 10) / 10.0 :
                                0.0
                ))
                .collect(Collectors.toList());

        return ResultVO.success("查询成功", result);
    }
}
